/*
 ============================================================================
 Name        : mysql_util.c
 Author      : ljf
 Version     :
 Copyright   : Your copyright notice
 Description : Connect Mysql utils
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mysql_util.h"
#include "log_util.h"

MYSQL g_conn; // mysql 连接
MYSQL_RES *g_res; // mysql 记录集
MYSQL_ROW g_row; // 字符串数组，mysql 记录行

#define MAX_BUF_SIZE 1024 // 缓冲区最大字节数


#define ADD_TH_ITEM "INSERT INTO `fa_datamanagement_thinfo` (`devId`, `temp`, `humi`, `timestamp`, `reportip`) VALUES ('%s','%s','%s','%s','%s')"
#define ADD_TH_ITEM_NO_IP "INSERT INTO `fa_datamanagement_thinfo` (`devId`, `temp`, `humi`, `timestamp`) VALUES ('%s','%s','%s','%s')"

/******************************************
*
*		打印最后一次错误
*
******************************************/
void print_mysql_error(const char *msg) 
{
    if (msg)
        ljf_err("%s: %s\n", msg, mysql_error(&g_conn));
    else
        puts(mysql_error(&g_conn));
}

int executesql(const char * sql) 
{
	log_sql("{%s;}\n", sql);
    /*query the database according the sql*/
    if (mysql_real_query(&g_conn, sql, strlen(sql)))
	{
		ljf_err("[%s] exec failed!!\n",sql);
		print_mysql_error(NULL);
        return -1;
    }
    return 0;
}

int list_thinfo()
{
	char sql[MAX_BUF_SIZE];
    if (executesql("select * from fa_datamanagement_thinfo")){
        return -1;
    }
	
	g_res = mysql_store_result(&g_conn); // 从服务器传送结果集至本地，mysql_use_result直接使用服务器上的记录集

	int iNum_rows = mysql_num_rows(g_res); // 得到记录的行数
    int iNum_fields = mysql_num_fields(g_res); // 得到记录的列数

    ljf_info("共%d个记录，每个记录%d字段\n", iNum_rows, iNum_fields);

    ljf_info("id\t编号\t温度\t湿度\t更新时间\n");

    while ((g_row=mysql_fetch_row(g_res))) // 打印结果集
        ljf_info("%s\t%s\t%s\t%s\t%s\n", g_row[0], g_row[1],g_row[2],g_row[3],g_row[4]); // 第一，第二字段

    mysql_free_result(g_res); // 释放结果集

}
/******************************************************************************


	Add temp and humi info to databases


******************************************************************************/
int add_thinfo(char *devId, char *temp, char *humi, char *timeStamp, char *rpt_ip)
{
	int ret = 0;
	char sql[MAX_BUF_SIZE] = {0};
	if((devId != NULL) && (temp != NULL) && (humi != NULL) && (timeStamp != NULL))
	{
		if(rpt_ip == NULL) //report ip is NULL
		{
			sprintf(sql, ADD_TH_ITEM_NO_IP, devId, temp, humi, timeStamp);
		}
		else
		{
			sprintf(sql, ADD_TH_ITEM, devId, temp, humi, timeStamp, rpt_ip);
		}
	}
	
    if (executesql(sql))
    {
		ret = -1;
	}
    return ret;
}

/*

初始化mysql连接

*/ 
int init_mysql(char *host_name, char *user_name, char *passwd, char *db_name, unsigned int db_port)
{
	char val = 1;
	MYSQL *mysql;
    //init the database connection
    mysql_init(&g_conn);
	mysql_options(&g_conn, MYSQL_OPT_RECONNECT, (char *)&val); 
	
    /*设置字符编码,可能会乱码*/
    mysql_query(&g_conn,"set names utf-8");

	/* connect the database */
    if(!mysql_real_connect(&g_conn, host_name, user_name, passwd, db_name, db_port, NULL, 0))
    {
    	printf("connect failed!!\n");
		print_mysql_error(NULL);
        return -1;
    }
    // 是否连接已经可用
    //if (executesql("set names utf8")) // 如果失败
       // return -1;
    return 0; // 返回成功
}

int deinit_mysql()
{
	mysql_close(&g_conn); // 关闭链接
}


